import pyautogui
import pygetwindow
import win32con
import win32gui

"""
这个线程运行鼠标的点击和输入事件，根据提供的股票代码来进行交易和买入
"""

class AutoWorker():

    def __init__(self):
        super().__init__()
        print('**AutoWorker** has init autoworker')
        # 设置工作状态与初始num数值

    # def __del__(self):
    #     # 线程状态改变与线程终止
    #     self.wait()

    def start_buy(self, stock=None, value=None):
        print('**AutoWorker** start buy', stock)
        self.stock = stock
        self.value = value
        self.auto_buy()
        # super().start()

    def start_sell(self, stock=None, value=None):
        print('**AutoWorker** start sell', stock)
        self.stock = stock
        self.value = value
        self.auto_sell()

    def test_gui(self):
        print('**AutoWorker** test_gui')
        wins = pygetwindow.getWindowsWithTitle('无标题')
        print('**AutoWorker**', wins)
        if len(wins) == 1:
            win = wins[0]
            win.maximize()
            win.activate()
            # win32gui.BringWindowToTop(win._hWnd)
            # win32gui.SetForegroundWindow(win._hWnd)
            # win32gui.SetActiveWindow(win._hWnd)
        pyautogui.typewrite('Hello World!')

    def auto_sell(self):
        print('**AutoWorker** start work')
        print("**AutoWorker** has started one action")
        self.choice_win()
        self.activate_win()
        work_list = [self.click_SELL, self.input_CODE, self.input_PRI, self.click_NUMB, self.choice_NUMB, self.input_NUMB]
        for work in work_list:
            if work() is None:
                continue
            else:
                break
        print("**AutoWorker** has finished one action")

    def auto_buy(self):
        print('**AutoWorker** start work')
        print("**AutoWorker** has started one action")
        self.choice_win()
        self.activate_win()
        work_list = [self.click_BUY, self.input_CODE, self.input_PRI, self.click_NUMB, self.choice_NUMB, self.input_NUMB]
        for work in work_list:
            if work() is None:
                continue
            else:
                break
        print("**AutoWorker** has finished one action")

    def choice_win(self):
        wins = pygetwindow.getWindowsWithTitle('网上股票交易系统5.')
        if len(wins) == 1:
            win = wins[0]
        else:
            wins = pygetwindow.getWindowsWithTitle('无标题')
            win = wins[0]
        print('**AutoWorker** get wins', win)
        self.win = win

    def activate_win(self):
        print('**AutoWorker** 置顶窗口前')
        win32gui.ShowWindow(self.win._hWnd, win32con.SW_SHOWNORMAL)
        win32gui.BringWindowToTop(self.win._hWnd)
        win32gui.SetForegroundWindow(self.win._hWnd)
        print('**AutoWorker** 置顶窗口后')

    def click_BUY(self):
        pyautogui.press('f1')     # press the F1 key
        # pyautogui.click(x=40, y=77)

    def click_SELL(self):
        pyautogui.press('f2')  # press the F1 key
        # pyautogui.click(x=40, y=77)

    def input_CODE(self):
        """ 选择并输入股票代码 """
        # pyautogui.click(x=302, y=111)
        x, y = self.win.topleft
        pyautogui.doubleClick(x=x + 308, y=y + 120)
        # pyautogui.press('enter')
        self.repeat_backspace()
        print('**AutoWorker** get wins', self.stock.code_without_prefix)
        pyautogui.typewrite(str(self.stock.code_without_prefix))

    def input_PRI(self):
        """ 选择并输入价格 """
        # pyautogui.click(x=310, y=153)
        # self.repeat_backspace()
        pyautogui.press('tab')
        pyautogui.typewrite(str(self.stock.pri))

    def click_NUMB(self):
        """ 选择数量 """
        # pyautogui.click(x=267, y=185)
        pyautogui.press('tab')

    def choice_NUMB(self):
        """ 选择交易金额 """
        value_dict = {
            '五分之一': 0.2,
            '三分之一': 0.33,
            '二分之一': 0.5,
            '三分之二': 0.66
        }
        self.now_stock_pri = self.stock.pri
        # self.numb =
        print_value = ['{}(取整{}股)'.format(key, int(value*self.value/self.now_stock_pri)//100*100)for key, value in value_dict.items()]
        rep = pyautogui.confirm(text='请输入买入的金额，目前您的资金池为{}，您选择交易的股票为【{}】，股票代码为【{}】'.
                                format(self.value, self.stock.name, self.stock.code),
                                title='持仓选择，并确认交易',
                                buttons=print_value)
        print('**AutoWorker** has get rep', rep)
        if rep is None:
            self.numb = 0
            return False
        else:
            self.numb = int(value_dict[rep[0:4]] * int(self.value) / self.now_stock_pri) // 100 * 100
            print('**AutoWorker**', self.numb)

    def input_NUMB(self):
        """ 输入交易金额 """
        # pyautogui.click(x=307, y=194)
        pyautogui.typewrite(str(self.numb))

    def ultimatum(self):
        info = '你选择交易的股票是【{}】 现价【{}】 交易股数【{}】，是否确认交易？'.\
            format(self.stock.name, self.now_stock_pri, self.numb)
        rep = pyautogui.confirm(text=info, title='交易前的最后确认', buttons=['交易', '放弃'])
        if rep == '交易':
            pass
        else:
            pass

    def repeat_backspace(self, time=6):
        for i in range(time):
            pyautogui.press('backspace')


